package es.esi.gemde.methodmanager;

import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;

import es.esi.gemde.methodmanager.service.IMethodManagementService;
import es.esi.gemde.methodmanager.service.impl.Method;
import es.esi.gemde.methodmanager.service.impl.MethodManagementService;

/**
 * The activator class controls the plug-in life cycle
 */
public class MethodManagerPlugin extends AbstractUIPlugin {

	// The plug-in ID
	public static final String PLUGIN_ID = "es.esi.gemde.methodmanager";
	
	// Extension point ID
	private static final String METHOD_EXTENSION_ID = "es.esi.gemde.methodmanager.method";

	// The shared instance
	private static MethodManagerPlugin plugin;
	private static MethodManagementService service = new MethodManagementService();
	
	/**
	 * The constructor
	 */
	public MethodManagerPlugin() {
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
	 */
	public void start(BundleContext context) throws Exception {
		super.start(context);
		plugin = this;
		
		loadMethodExtensions();
		// TODO: Add a preferences page to initialize the active method in GEMDE!!
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext context) throws Exception {
		plugin = null;
		super.stop(context);
	}

	/**
	 * Returns the shared instance
	 *
	 * @return the shared instance
	 */
	public static MethodManagerPlugin getDefault() {
		return plugin;
	}
	
	public static IMethodManagementService getService() {
		return service;
	}

	/**
	 * Internal method to load methodology adapters.
	 */
	private void loadMethodExtensions() {
		// Get the elements contributing in the extension point
		IConfigurationElement[] config = Platform.getExtensionRegistry().getConfigurationElementsFor(METHOD_EXTENSION_ID);
		
		for (IConfigurationElement method : config) {
			try {
				// Get the attributes of the extension and check them.
				String name = method.getAttribute("name");
				service.registerMethod(new Method(name));
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
